import { InjectionKey, PropType } from 'vue';

type TMode = 'edit' | 'view' | 'disable';

const formModeProviderKey = 'formModeProviderKey' as unknown as InjectionKey<{ mode: TMode }>;

export const FormMode = defineComponent({
  props: {
    mode: {
      type: String as PropType<TMode>,
      default: 'edit'
    }
  },
  setup(props, { slots }) {
    const modeCtx = reactive({
      mode: props.mode
    });
    provide(formModeProviderKey, modeCtx);

    watch(
      () => props.mode,
      () => {
        modeCtx.mode = props.mode;
      }
    );

    return () => {
      return <>{slots.default?.()}</>;
    };
  }
});

export const useFormMode = () => {
  const modeCtx = inject(formModeProviderKey, null);
  return modeCtx;
};
